import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

public class PrepareResponse {

	public synchronized InetAddress ipFromString(String ipstring)
			throws UnknownHostException {

		String[] splitAdd = ipstring.trim().split("/");
		return InetAddress.getByName(splitAdd[1]);
	}

	public static synchronized void removeEntryFromPongWaitList(
			NodeTriple nodeTriple) {

		for (WaitingQueueForPongEntry eachEntry : WaitingQueueForPong
				.getQueue()) {
			if (null != eachEntry) {
				if (eachEntry.getNodeTriple().nodeID.trim().equalsIgnoreCase(
						nodeTriple.nodeID.trim())) {
					int index = WaitingQueueForPong.getQueue().indexOf(
							eachEntry);
					WaitingQueueForPong.getQueue().set(index, null);

				}
			}
		}

	}

	public static synchronized void removeEntryFromFindNodeWaitList(
			NodeTriple nodeTriple) {

		for (WaitingQueueForFindNodeResponseEntry eachEntry : WaitingQueueForFindNodeResponse
				.getQueue()) {
			if (null != eachEntry) {
				if (eachEntry.getNodeTriple().nodeID.trim().equalsIgnoreCase(
						nodeTriple.nodeID.trim())) {
					int index = WaitingQueueForFindNodeResponse.getQueue()
							.indexOf(eachEntry);
					WaitingQueueForFindNodeResponse.getQueue().set(index, null);
				}
			}
		}

	}

	public synchronized void processMessage(String receivedMsg)
			throws Exception {

		String[] parsedMessage = parseString(receivedMsg);

		NodeTriple nodeTriple = new NodeTriple();
		nodeTriple.nodeID = parsedMessage[1];

		nodeTriple.ip = this.ipFromString(parsedMessage[2]);
		nodeTriple.port = Integer.parseInt(parsedMessage[3]);

		BucketOperations bucketOperations = new BucketOperations();
		bucketOperations.addTripleIntoBucket(nodeTriple);

		if (parsedMessage[0].contains(Properties.PING_HEADER)) {

			sendPong(nodeTriple);

		} else if (parsedMessage[0].contains(Properties.PONG_HEADER)) {

			removeEntryFromPongWaitList(nodeTriple);

		} else if (parsedMessage[0]
				.contains(Properties.FIND_NODE_REQUEST_HEADER)) {

			bucketOperations.findNode(nodeTriple.nodeID);
			

		} else if (parsedMessage[0]
				.contains(Properties.FIND_NODE_RESPONSE_HEADER)) {

			removeEntryFromFindNodeWaitList(nodeTriple);

		} else {

			System.out.println("Invalid Request received:" + parsedMessage[0]);

		}

	}

	public synchronized String[] parseString(String receivedMsg) {

		return receivedMsg.trim().split(Properties.MSG_SEPERATOR);
	}

	public synchronized String prepareHeader(String messageType) {

		return messageType + Properties.MSG_SEPERATOR
				+ SelfInfo.nodeTriple.nodeID + Properties.MSG_SEPERATOR
				+ SelfInfo.nodeTriple.ip + Properties.MSG_SEPERATOR
				+ SelfInfo.nodeTriple.port;
	}

	public synchronized void sendPong(NodeTriple nodeTriple) throws Exception {

		String header = prepareHeader(Properties.PONG_HEADER);
		SendingService.getSendingService().send(header, nodeTriple.ip,
				nodeTriple.port);

	}

}
